#include "stm32f1xx_hal.h"
#include "uart.h"

extern UART_HandleTypeDef huart1;
extern UART_HandleTypeDef huart2;
extern UART_HandleTypeDef huart3;

UART_CHAN_T uart_chan[UART_CHANNEL_NUM];

static unsigned char debug_rx_buf[DEBUG_RX_BUF_SIZE];
static unsigned char bluetooth_rx_buf[BLUETOOTH_RX_BUF_SIZE];
static unsigned char backup_rx_buf[BACKUP_RX_BUF_SIZE];

static unsigned char uart_rxdata[UART_CHANNEL_NUM];

extern void uart_chan_init(void)
{
	int i = 0;

    uart_chan[0].husart = &huart1;
    uart_chan[1].husart = &huart2;
    uart_chan[2].husart = &huart3;
    
	for (i = 0; i < (int)UART_CHANNEL_NUM; i ++)
	{
		uart_chan[i].rx_in = 0;
		uart_chan[i].rx_out = 0; 
		HAL_UART_Receive_IT ( uart_chan[i].husart , &uart_rxdata[i] , 1 );

		switch ((UART_CHANNEL_EU)i)
		{
			case UART_CHANNEL_DEBUG :
				uart_chan[i].rx_size = DEBUG_RX_BUF_SIZE;
				uart_chan[i].rx_buf = debug_rx_buf;
				break;
			case UART_CHANNEL_BLUETOOTH :
				uart_chan[i].rx_size = BLUETOOTH_RX_BUF_SIZE;
				uart_chan[i].rx_buf = bluetooth_rx_buf;
				break;
			case UART_CHANNEL_BACKUP :
				uart_chan[i].rx_size = BACKUP_RX_BUF_SIZE;
				uart_chan[i].rx_buf = backup_rx_buf;
				break;
			default:
				break;
		}
	}
}

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *UartHandle)
{
	char uart_num;

	if ( UartHandle == &huart1 )			uart_num = 0;
	else if ( UartHandle == &huart2 )		uart_num = 1;
	else if ( UartHandle == &huart3 )		uart_num = 2;
	
	uart_chan[uart_num].rx_buf[uart_chan[uart_num].rx_in] = uart_rxdata[uart_num];
	uart_chan[uart_num].rx_in++;
	if(uart_chan[uart_num].rx_in >= uart_chan[uart_num].rx_size)
	{
		uart_chan[uart_num].rx_in = 0 ;
	}

    uart_chan[uart_num].last_recv_time = HAL_GetTick () ;
	HAL_UART_Receive_IT ( uart_chan[uart_num].husart , &uart_rxdata[uart_num] , 1 );
}

extern bool UART_Rx_Empty (unsigned char chan)
{
    return (bool)(uart_chan[chan].rx_in == uart_chan[chan].rx_out);
}

extern unsigned int Uart_Get_Last_Recv_Time(unsigned char chan)
{
    if(chan >= UART_CHANNEL_NUM)
        return 0 ;
    
   return uart_chan[chan].last_recv_time ;
}

extern bool Uart_Get_Char ( uint8_t chan , uint8_t *ptr )
{
	if(chan >= UART_CHANNEL_NUM)
		return false ;

	if(uart_chan[chan].rx_in != uart_chan[chan].rx_out)// Rx buffer not empty
	{
		if(ptr == NULL)      return false ;

		*ptr = uart_chan[chan].rx_buf[uart_chan[chan].rx_out] ;

		uart_chan[chan].rx_out ++ ;
		if(uart_chan[chan].rx_out >= uart_chan[chan].rx_size)
		{
			uart_chan[chan].rx_out = 0 ;
		}
		return true ;
	}
    return false ;
}


/* end of file */

